import 'dart:async';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../function/states/private_conversation_state.dart';
import '../../function/states/user_state.dart';
import '../../function/routes/app_route_manager.dart';
import '../../function/widgets/animated_tap_widget.dart';
import '../../function/widgets/toast_widget.dart';

/// 视频通话页面
class VideoCallPage extends StatefulWidget {
  final String targetUserId; // 目标用户ID

  const VideoCallPage({super.key, required this.targetUserId});

  @override
  State<VideoCallPage> createState() => _VideoCallPageState();
}

class _VideoCallPageState extends State<VideoCallPage>
    with TickerProviderStateMixin {
  late AnimationController _pulseController;
  late AnimationController _waveController1;
  late AnimationController _waveController2;
  late AnimationController _waveController3;
  late Animation<double> _pulseAnimation;
  late Animation<double> _waveAnimation1;
  late Animation<double> _waveAnimation2;
  late Animation<double> _waveAnimation3;

  Timer? _callTimer;
  bool _isCallEnded = false;

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _startCallTimer();
  }

  @override
  void dispose() {
    _pulseController.dispose();
    _waveController1.dispose();
    _waveController2.dispose();
    _waveController3.dispose();
    _callTimer?.cancel();
    super.dispose();
  }

  /// 初始化动画
  void _initializeAnimations() {
    // 脉冲动画控制器
    _pulseController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );

    // 水波动画控制器
    _waveController1 = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    );
    _waveController2 = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    );
    _waveController3 = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    );

    // 脉冲动画
    _pulseAnimation = Tween<double>(begin: 1.0, end: 1.3).animate(
      CurvedAnimation(parent: _pulseController, curve: Curves.easeInOut),
    );

    // 水波动画
    _waveAnimation1 = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(parent: _waveController1, curve: Curves.easeOut));
    _waveAnimation2 = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(parent: _waveController2, curve: Curves.easeOut));
    _waveAnimation3 = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(parent: _waveController3, curve: Curves.easeOut));

    // 启动动画
    _pulseController.repeat(reverse: true);

    // 启动水波动画，错开时间
    _waveController1.repeat();
    Future.delayed(const Duration(milliseconds: 1000), () {
      if (mounted) _waveController2.repeat();
    });
    Future.delayed(const Duration(milliseconds: 2000), () {
      if (mounted) _waveController3.repeat();
    });
  }

  /// 开始通话计时器
  void _startCallTimer() {
    _callTimer = Timer(const Duration(seconds: 12), () {
      if (!_isCallEnded && mounted) {
        _handleCallTimeout();
      }
    });
  }

  /// 处理通话超时
  void _handleCallTimeout() {
    _isCallEnded = true;
    _callTimer?.cancel();

    // 发送通话失败消息
    _sendCallFailureMessage();

    // 显示提示
    ToastWidget.showWarning('The other party did not respond');

    // 返回上一页
    AppRouteManager.goBack();
  }

  /// 处理用户取消通话
  void _handleUserCancel() {
    _isCallEnded = true;
    _callTimer?.cancel();

    // 显示提示
    ToastWidget.showWarning('You hung up the call.');

    // 返回上一页
    AppRouteManager.goBack();
  }

  /// 发送通话失败消息
  void _sendCallFailureMessage() {
    final currentUser = UserState.getCurrentUserInfo();
    if (currentUser != null) {
      PrivateConversationState.sendTextMessage(
        senderId: currentUser.userId,
        receiverId: widget.targetUserId,
        content: 'Call failed - no response',
      );
    }
  }

  /// 获取目标用户信息
  Map<String, String>? _getTargetUserInfo() {
    return PrivateConversationState.getUserInfo(widget.targetUserId);
  }

  @override
  Widget build(BuildContext context) {
    final targetUserInfo = _getTargetUserInfo();
    final targetUserName = targetUserInfo?['userName'] ?? 'Unknown User';
    final targetUserAvatar =
        targetUserInfo?['userAvatar'] ?? 'assets/images/avatar1.png';

    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Stack(
          children: [
            // 背景用户头像（模糊效果）
            Positioned.fill(
              child: Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(targetUserAvatar),
                    fit: BoxFit.cover,
                  ),
                ),
                child: BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 15.0, sigmaY: 15.0),
                  child: Container(color: Colors.black.withOpacity(0.3)),
                ),
              ),
            ),

            // 主要内容区域
            SafeArea(
              child: Column(
                children: [
                  // 中间用户头像区域
                  Expanded(
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          // 用户头像和扩散效果
                          _buildUserAvatarWithPulse(targetUserAvatar),

                          SizedBox(height: 24.h),

                          // 用户名
                          Text(targetUserName)
                              .fontSize(24.sp)
                              .textColor(Colors.white)
                              .fontWeight(FontWeight.w600)
                              .fontFamily(
                                GoogleFonts.quicksand(
                                  fontWeight: FontWeight.w600,
                                ).fontFamily,
                              ),

                          SizedBox(height: 8.h),

                          // 通话状态
                          Text('Calling...')
                              .fontSize(16.sp)
                              .textColor(Colors.white.withOpacity(0.8))
                              .fontWeight(FontWeight.w400)
                              .fontFamily(
                                GoogleFonts.quicksand(
                                  fontWeight: FontWeight.w400,
                                ).fontFamily,
                              ),
                        ],
                      ),
                    ),
                  ),

                  // 底部挂断按钮
                  _buildHangUpButton(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建用户头像和水波效果
  Widget _buildUserAvatarWithPulse(String avatarPath) {
    return AnimatedBuilder(
      animation: Listenable.merge([
        _pulseAnimation,
        _waveAnimation1,
        _waveAnimation2,
        _waveAnimation3,
      ]),
      builder: (context, child) {
        return Stack(
          alignment: Alignment.center,
          children: [
            // 水波效果 - 第三层
            _buildWaveRing(
              size: 300.w,
              animation: _waveAnimation3,
              opacity: 0.1,
              delay: 0.0,
            ),

            // 水波效果 - 第二层
            _buildWaveRing(
              size: 250.w,
              animation: _waveAnimation2,
              opacity: 0.2,
              delay: 0.0,
            ),

            // 水波效果 - 第一层
            _buildWaveRing(
              size: 200.w,
              animation: _waveAnimation1,
              opacity: 0.3,
              delay: 0.0,
            ),

            // 脉冲环效果
            Container(
              width: 160.w * _pulseAnimation.value,
              height: 160.w * _pulseAnimation.value,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                  color: Colors.white.withOpacity(0.4),
                  width: 1.5.w,
                ),
              ),
            ),

            // 用户头像
            Container(
              width: 120.w,
              height: 120.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 2.w),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.4),
                    blurRadius: 15.r,
                    offset: Offset(0, 8.h),
                  ),
                ],
              ),
              child: ClipOval(
                child: Image.asset(avatarPath, fit: BoxFit.cover),
              ),
            ),
          ],
        );
      },
    );
  }

  /// 构建水波环
  Widget _buildWaveRing({
    required double size,
    required Animation<double> animation,
    required double opacity,
    required double delay,
  }) {
    return AnimatedBuilder(
      animation: animation,
      builder: (context, child) {
        final scale = 0.8 + (0.4 * animation.value);
        final alpha = (1.0 - animation.value) * opacity;

        return Transform.scale(
          scale: scale,
          child: Container(
            width: size,
            height: size,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(
                color: Colors.white.withOpacity(alpha),
                width: 2.w,
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建挂断按钮
  Widget _buildHangUpButton() {
    return Container(
      padding: EdgeInsets.only(bottom: 40.h),
      child: AnimatedTapWidget(
        onTap: _handleUserCancel,
        child: Container(
          width: 64.w,
          height: 64.w,
          decoration: BoxDecoration(
            color: Colors.red,
            shape: BoxShape.circle,
            image: DecorationImage(
              image: AssetImage('assets/images/hand_off.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }
}
